/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.web.action.debt;

import java.security.Principal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.common.model.Student;
import ar.uba.fi.posgrado.common.model.User;
import ar.uba.fi.posgrado.common.service.StudentService;
import ar.uba.fi.posgrado.common.service.UserService;
import ar.uba.fi.posgrado.common.util.CommonUtils;
import ar.uba.fi.posgrado.economy.model.Debt;
import ar.uba.fi.posgrado.economy.model.DebtStatus;
import ar.uba.fi.posgrado.economy.model.DebtType;
import ar.uba.fi.posgrado.economy.service.DebtService;
import ar.uba.fi.posgrado.economy.web.form.debt.DebtForm;

/**
 * Busca deudas por ciertas condiciones.<br>
 * Por el momento las busquedas son tomadas como AND logicos de
 * lo que viene.<br>
 * Busca por Cuenta exacta y Alumno exacto.<br>
 * Las fecha de venc es Menor o Igual y la desde es Mayor o Igual.<br>
 * Lo otro es exacto.<br>
 *
 * Filtra los resultados por el usuario.<br>
 * 
 * @author nicolas.gonzalez
 * @see Action
 */
public class FindDebtsByConditionsAction extends Action {

    /** Logger */
    private static Logger logger = Logger.getLogger(FindDebtsByConditionsAction.class);
    
    private StudentService studentService;
    private DebtService debtService;
    private CourseService courseService;
    private UserService userService;


    /**
     * @param debtService the debtService to set
     */
    public void setDebtService(DebtService debtService) {
        this.debtService = debtService;
    }
    
    /**
     * @param studentService the studentService to set
     */
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * @param courseService the courseService to set
     */
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

    
    /**
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unchecked")
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Por buscar deudas por varios condiciones ingresadas por el usuario...");
        }
        DebtForm form = (DebtForm)actionForm;

        Principal ppal =  request.getUserPrincipal();
        String userName = ppal.getName();
        User user = this.userService.getUserByName(userName);
        
        Debt debt = new Debt(); 
        if (form.getStudentId() != null && !form.getStudentId().equals(new Long(0))) {
            Student student = this.studentService.getById(form.getStudentId());
            debt.setStudent(student);
            
            logger.debug("Agregando usuario a la condicion de busqueda de deudas ...");
        }
        if (StringUtils.isNotEmpty(form.getCourseSelected())) {
            Long courseSelectedId = new Long(form.getCourseSelected());
            Course course = this.courseService.getById(courseSelectedId);
            debt.setCourse(course);

            logger.debug("Agregando curso a la condicion de busqueda de deudas ...");
        }
        if (StringUtils.isNotEmpty(form.getValidityFrom())) {
            debt.setValidityFrom(CommonUtils.toDateFromStringStandard(form.getValidityFrom()));
            
            logger.debug("Agregando fecha desde a la condicion de busqueda de deudas ...");
        }
        if (StringUtils.isNotEmpty(form.getExpiry())) {
            debt.setExpiry(CommonUtils.toDateFromStringStandard(form.getExpiry()));
            
            logger.debug("Agregando fecha de expiracion a la condicion de busqueda de deudas ...");
        }
        if (StringUtils.isNotEmpty(form.getDebtStatusSelected())) {
            debt.setDebtStatus(DebtStatus.fromStringValue(form.getDebtStatusSelected()));
            
            logger.debug("Agregando estado de deuda desde a la condicion de busqueda de deudas ...");
        }
        if (StringUtils.isNotEmpty(form.getDebtTypeSelected())) {
            Long debtTypeSelectedId = new Long(form.getDebtTypeSelected());
            DebtType debtType = this.debtService.getDebtTypeById(debtTypeSelectedId);
            debt.setDebtType(debtType);
            
            logger.debug("Agregando tipo de concepto a la condicion de busqueda de deudas ...");
        }

        List<Debt> debts = this.debtService.getDebtsByConditions(debt);
        debts = this.debtService.filter(debts, user);

        if (logger.isDebugEnabled()) {
            logger.debug("Cantidad de deudas encontradas con condiciones: " + debts.size());
        }
        form.setDebts(debts);
        
        logger.info("Mostrar pantalla de busqueda de deudas por condiciones finalizado");
        return mapping.findForward("success");
    }
    
    
}
